import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=110 lang=java
 *
 * [110] 平衡二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        return getHeight(root)==-1? false:true;
    }

    //递归法，若二叉树左右子树高度大于1，则返回-1，否则返回最大高度即可。
    public int getHeight(TreeNode root){
        if(root==null) return 0;
        int leftheight=getHeight(root.left);
        if(leftheight==-1){
            return -1;
        }
        int rightheight=getHeight(root.right);
        if(rightheight==-1){
            return -1;
        }
        if(Math.abs(leftheight-rightheight)>1){
            return -1;
        }
        return Math.max(leftheight, rightheight)+1;
    }
}
// @lc code=end

